package app

// 每一个设备的任务
// 不断获取任务
// 如果任务为空, 那么可以结束, 可以获取执行情况

// 设备任务
type dtProduct struct {
	*Product
	sendCount int
	isDone    bool
}

type DeviceTask struct {
	*Device
	taskInfo *Task

	nextC      chan *dtProduct
	productMap map[uint32]*dtProduct

	isDone         bool
	successCount   int
	doneProductMap map[uint32]*dtProduct
}

func NewDeviceTask(taskInfo *Task, device *Device, product []*Product) *DeviceTask {
	dt := &DeviceTask{
		taskInfo: taskInfo,
		Device:   device,

		productMap:     make(map[uint32]*dtProduct, len(product)),
		doneProductMap: make(map[uint32]*dtProduct, len(product)),
		successCount:   0,

		nextC: make(chan *dtProduct, 0),
	}

	for _, p := range product {
		tmp := &dtProduct{
			Product:   p,
			sendCount: 0,
			isDone:    false,
		}
		dt.productMap[p.ProductId] = tmp
		dt.doneProductMap[p.ProductId] = tmp
	}

	go dt.run()

	return dt
}

func (dt *DeviceTask) run() {
	for i := 0; i < dt.taskInfo.Retry; i++ {
		for _, product := range dt.productMap {
			if product.isDone {
				continue
			}
			dt.nextC <- product
			product.sendCount++
		}
	}
	dt.isDone = true
	close(dt.nextC)
}

func (dt *DeviceTask) AddDoneProdeuct(productId uint32) {
	p, has := dt.doneProductMap[productId]
	if has {
		dt.successCount++
		p.isDone = true
	}

}

func (dt *DeviceTask) Next() (p *Product) {
	if dt.isDone {
		return nil
	}
	tmp, ok := <-dt.nextC
	if ok {
		return tmp.Product
	}
	return nil
}

// 获取设备的当前状态
func (dt *DeviceTask) Status() {

}
